import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useSoundStore = defineStore('sound', () => {
  const isEnabled = ref(true)
  const volume = ref(0.5)
  const audioContext = ref(null)
  const sounds = ref({})

  // 音效配置
  const soundConfig = {
    click: {
      frequency: 800,
      duration: 0.1,
      type: 'sine'
    },
    hover: {
      frequency: 600,
      duration: 0.05,
      type: 'sine'
    },
    success: {
      frequency: [523, 659, 784],
      duration: 0.2,
      type: 'sine'
    },
    error: {
      frequency: [200, 150],
      duration: 0.3,
      type: 'sawtooth'
    },
    welcome: {
      frequency: [261, 329, 392, 523],
      duration: 0.3,
      type: 'sine'
    },
    notification: {
      frequency: 440,
      duration: 0.2,
      type: 'triangle'
    }
  }

  // 初始化音效系统
  const initSound = () => {
    const savedEnabled = localStorage.getItem('sound-enabled')
    const savedVolume = localStorage.getItem('sound-volume')
    
    if (savedEnabled !== null) {
      isEnabled.value = savedEnabled === 'true'
    }
    
    if (savedVolume !== null) {
      volume.value = parseFloat(savedVolume)
    }

    // 创建音频上下文
    try {
      audioContext.value = new (window.AudioContext || window.webkitAudioContext)()
    } catch (error) {
      console.warn('Web Audio API not supported')
    }
  }

  // 播放音效
  const playSound = (soundName) => {
    if (!isEnabled.value || !audioContext.value) return

    const config = soundConfig[soundName]
    if (!config) return

    // 恢复音频上下文（如果被暂停）
    if (audioContext.value.state === 'suspended') {
      audioContext.value.resume()
    }

    const frequencies = Array.isArray(config.frequency) 
      ? config.frequency 
      : [config.frequency]

    frequencies.forEach((freq, index) => {
      setTimeout(() => {
        playTone(freq, config.duration, config.type)
      }, index * config.duration * 1000)
    })
  }

  // 播放单个音调
  const playTone = (frequency, duration, type = 'sine') => {
    if (!audioContext.value) return

    const oscillator = audioContext.value.createOscillator()
    const gainNode = audioContext.value.createGain()

    oscillator.connect(gainNode)
    gainNode.connect(audioContext.value.destination)

    oscillator.frequency.setValueAtTime(frequency, audioContext.value.currentTime)
    oscillator.type = type

    gainNode.gain.setValueAtTime(0, audioContext.value.currentTime)
    gainNode.gain.linearRampToValueAtTime(volume.value * 0.3, audioContext.value.currentTime + 0.01)
    gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.value.currentTime + duration)

    oscillator.start(audioContext.value.currentTime)
    oscillator.stop(audioContext.value.currentTime + duration)
  }

  // 切换音效开关
  const toggleSound = () => {
    isEnabled.value = !isEnabled.value
    localStorage.setItem('sound-enabled', isEnabled.value.toString())
    
    if (isEnabled.value) {
      playSound('notification')
    }
  }

  // 设置音量
  const setVolume = (newVolume) => {
    volume.value = Math.max(0, Math.min(1, newVolume))
    localStorage.setItem('sound-volume', volume.value.toString())
  }

  // 播放点击音效
  const playClick = () => {
    playSound('click')
  }

  // 播放悬停音效
  const playHover = () => {
    playSound('hover')
  }

  // 播放成功音效
  const playSuccess = () => {
    playSound('success')
  }

  // 播放错误音效
  const playError = () => {
    playSound('error')
  }

  // 清理资源
  const cleanup = () => {
    if (audioContext.value) {
      audioContext.value.close()
    }
  }

  return {
    isEnabled,
    volume,
    initSound,
    playSound,
    toggleSound,
    setVolume,
    playClick,
    playHover,
    playSuccess,
    playError,
    cleanup
  }
}) 